package org.brownflat.lighthouse.monitor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executor;

import org.apache.log4j.Logger;

public class SimpleMonitoringService implements MonitoringService {

	private Executor executor;
	private List<LighthouseTask> active = new ArrayList<LighthouseTask>();
	private List<LighthouseTask> paused = new ArrayList<LighthouseTask>();
	private static final Logger LOG = Logger.getLogger(SimpleMonitoringService.class);
	
	public SimpleMonitoringService(Executor executor) {
		this.executor = executor;
	}

	public SimpleMonitoringService(Executor executor, List<LighthouseTask> tasks) {
		this.executor = executor;
		paused.addAll(tasks);
	}
	
	public void addTask(LighthouseTask task) {
		this.paused.add(task);
	}
	
	public List<String> activeTasks() {
		List<String> values = new ArrayList<String>();
		for (LighthouseTask task : active) {
			values.add(task.getName());
		}
		return values;
	}
	
	public List<String> pausedTasks() {
		List<String> values = new ArrayList<String>();
		for (LighthouseTask task : paused) {
			values.add(task.getName());
		}
		return values;
	}
		
	@Override
	public boolean pause() {
		for (Iterator iterator = active.iterator(); iterator.hasNext();) {
			LighthouseTask task = (LighthouseTask) iterator.next();
			paused.add(task);
			iterator.remove();
		}
		return true;
	}
	
	@Override
	public boolean pause(String name) {
		for (Iterator iterator = active.iterator(); iterator.hasNext();) {
			LighthouseTask task = (LighthouseTask) iterator.next();
			if(task.getName().equals(name)) {
				paused.add(task);
				iterator.remove();
				return true;
			}
		}
		return false;
	}
	
	@Override
	public boolean start() {
		for (Iterator iterator = paused.iterator(); iterator.hasNext();) {
			LighthouseTask task = (LighthouseTask) iterator.next();
			active.add(task);
			iterator.remove();			
		}
		return true;
	}
	
	@Override
	public boolean start(String name) {
		for (Iterator iterator = paused.iterator(); iterator.hasNext();) {
			LighthouseTask task = (LighthouseTask) iterator.next();
			if(task.getName().equals(name)) {
				active.add(task);
				iterator.remove();
				return true;
			}
		}
		return false;
	}

	public void run() {
		for (LighthouseTask task : active) {
			LOG.debug("Executing " + task.getName());
			executor.execute(task);
		}
	}
}
